package com.itcast.demo.thread_test.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.beans.Visibility;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@EnableAsync
@Configuration
public class ThreadConfig {

    @Autowired
    private ThreadEntity threadEntity;

    @Bean(name = "asyncServiceExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        log.warn("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadEntity.getCore_pool_size());
        executor.setMaxPoolSize(threadEntity.getMax_pool_size());
        executor.setQueueCapacity(threadEntity.getQueue_capacity());
        executor.setKeepAliveSeconds(threadEntity.getKeep_alive_time());
        executor.setThreadNamePrefix(threadEntity.getThread_name_prefix());
        executor
                .setRejectedExecutionHandler(
                        new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务都完成再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }
}
